// Token存储键名
const TOKEN_KEY = 'AI_ASSISTANT_TOKEN'
const USER_INFO_KEY = 'AI_ASSISTANT_USER_INFO'

// 获取Token
export const getToken = (): string => {
  return localStorage.getItem(TOKEN_KEY) || ''
}

// 设置Token
export const setToken = (token: string): void => {
  localStorage.setItem(TOKEN_KEY, token)
}

// 移除Token
export const removeToken = (): void => {
  localStorage.removeItem(TOKEN_KEY)
}

// 用户信息相关操作
export interface UserInfo {
  id: number | string
  userName: string
  realName: string
  role: string
  avatar?: string
  token?: string
  permissions?: string[]
}

// 获取用户信息
export const getUserInfo = (): UserInfo | null => {
  const userInfoStr = localStorage.getItem(USER_INFO_KEY)
  if (!userInfoStr) return null
  try {
    return JSON.parse(userInfoStr)
  } catch (error) {
    console.error('Parse user info error:', error)
    return null
  }
}

// 设置用户信息
export const setUserInfo = (userInfo: UserInfo): void => {
  localStorage.setItem(USER_INFO_KEY, JSON.stringify(userInfo))
  localStorage.setItem('userRole', userInfo.role)
}

// 清除用户信息
export const removeUserInfo = (): void => {
  localStorage.removeItem(USER_INFO_KEY)
}

// 清除所有数据
export const clearStorage = (): void => {
  removeToken()
  removeUserInfo()
}

/**
 * 通用的本地存储操作
 */
// 存储数据
export const setStorage = (key: string, value: any): void => {
  if (typeof value === 'object') {
    localStorage.setItem(key, JSON.stringify(value))
  } else {
    localStorage.setItem(key, value)
  }
}

// 获取数据
export const getStorage = <T = any>(key: string, defaultValue: T | null = null): T | null => {
  const value = localStorage.getItem(key)
  if (value === null) return defaultValue
  try {
    return JSON.parse(value) as T
  } catch (e) {
    return value as unknown as T
  }
}

// 删除数据
export const removeStorage = (key: string): void => {
  localStorage.removeItem(key)
}

/**
 * 会话存储相关操作
 */
// 存储会话数据
export const setSessionStorage = (key: string, value: any): void => {
  if (typeof value === 'object') {
    sessionStorage.setItem(key, JSON.stringify(value))
  } else {
    sessionStorage.setItem(key, value)
  }
}

// 获取会话数据
export const getSessionStorage = <T = any>(key: string, defaultValue: T | null = null): T | null => {
  const value = sessionStorage.getItem(key)
  if (value === null) return defaultValue
  try {
    return JSON.parse(value) as T
  } catch (e) {
    return value as unknown as T
  }
}

// 删除会话数据
export const removeSessionStorage = (key: string): void => {
  sessionStorage.removeItem(key)
}

// 清除所有会话数据
export const clearSessionStorage = (): void => {
  sessionStorage.clear()
} 